package com.example.study.page.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PathMeasure
import android.graphics.RectF
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
import androidx.core.content.ContextCompat
import com.example.study.R
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.min
import kotlin.math.sin

/**
 * Created by lijinxi on 2024/2/28
 * @Description:
 */
class LotteryDiskView(context: Context, attrs: AttributeSet? = null) : View(context, attrs) {
    private val paint = Paint()
    private val rectArc = RectF()
    private var centerX = 0
    private var centerY = 0
    private var totalRotation = 0f
    private var prizes: MutableList<String> = ArrayList()
    private var prizeCount = 0
    private var animationDuration: Int = 20000 //默认值2000ms
    private var prizeColors: MutableList<Int> = ArrayList()
    private var prizeImages: MutableList<Drawable> = ArrayList()


    init {
        paint.isAntiAlias = true

        // 添加默认奖品
        prizes.add("谢谢参与")
        prizes.add("手机")
        prizes.add("充电宝")
        prizes.add("100元")
        prizes.add("200元")
        prizes.add("50元")

        prizeColors.add(Color.YELLOW)
        prizeColors.add(Color.RED)
        prizeColors.add(Color.GREEN)
        prizeColors.add(Color.BLUE)
        prizeColors.add(Color.CYAN)
        prizeColors.add(Color.MAGENTA)

        prizeImages.add(ContextCompat.getDrawable(context, R.drawable.whale)!!)
        prizeImages.add(ContextCompat.getDrawable(context, R.drawable.whale)!!)
        prizeImages.add(ContextCompat.getDrawable(context, R.drawable.whale)!!)
        prizeImages.add(ContextCompat.getDrawable(context, R.drawable.whale)!!)
        prizeImages.add(ContextCompat.getDrawable(context, R.drawable.whale)!!)
        prizeImages.add(ContextCompat.getDrawable(context, R.drawable.whale)!!)

        prizeCount = prizes.size
    }

    fun setPrizeList(prizes: List<String>?) {
        prizes?.let {
            if (it.isNotEmpty()) {
                this.prizes = prizes.toMutableList()
                prizeCount = prizes.size
                invalidate()  //更新视图
            }
        }
    }

    // 允许用户设置奖品及其对应的颜色
    fun setPrizesAndColors(prizes: List<String>?, prizeColors: List<Int>?) {
        if (!prizes.isNullOrEmpty() && prizeColors != null && prizeColors.size == prizes.size) {
            this.prizes = prizes.toMutableList()
            this.prizeColors = prizeColors.toMutableList()
            prizeCount = prizes.size
            invalidate() // 更新视图
        }
    }


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        centerX = width / 2
        centerY = height / 2
        val minSize = min(width, height)
        val arcSize = minSize * 0.9f
        rectArc.set(
            (centerX - arcSize / 2),
            (centerY - arcSize / 2),
            (centerX + arcSize / 2),
            (centerY + arcSize / 2)
        )
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 保存画布状态并设置旋转角度
        canvas.save()
        canvas.rotate(totalRotation, centerX.toFloat(), centerY.toFloat())

        paint.style = Paint.Style.FILL
        // 绘制每个奖品的扇区
        drawBackground(canvas)
        //绘制文字
        drawPrizeText(canvas)
        //绘制图标
        drawPrizesImages(canvas)

        canvas.restore()

        //绘制指针
        drawPointer(canvas)
    }

    private fun drawPointer(canvas: Canvas) {
        paint.color = Color.WHITE
        paint.style = Paint.Style.FILL

        val pointerWidth = width * 0.04f
        val pointerHeight = width * 0.15f
        val pointerPath = Path()

        // 设定指针的顶点（三角形形态）
        pointerPath.moveTo(centerX.toFloat(), centerY.toFloat() - pointerHeight)
        pointerPath.lineTo(centerX - pointerWidth / 2, centerY.toFloat())
        pointerPath.lineTo(centerX + pointerWidth / 2, centerY.toFloat())
        pointerPath.close()

        canvas.drawPath(pointerPath, paint)
    }

    private fun drawPrizesImages(canvas: Canvas) {
        for (i in 0 until prizeCount) {
            val startAngle = 360f * i / prizeCount
            val midAngle = startAngle + (360f / prizeCount) * 0.5f

            val rAngle = (midAngle * PI / 180.0) // 转换为弧度
            val imageRadius = rectArc.width() * 0.5 * 0.5 // 设置图片与圆心的距离（占半径的 75%）

            val imgX = centerX + (imageRadius * cos(rAngle)).toFloat()
            val imgY = centerY + (imageRadius * sin(rAngle)).toFloat()

            val bmpDrawable = prizeImages[i] as BitmapDrawable
            val image = bmpDrawable.bitmap

            // 计算图片宽和高的缩放比例
            val widthRatio = rectArc.height() * 0.15 / image.width
            val heightRatio = rectArc.height() * 0.15 / image.height
            val ratio = min(widthRatio, heightRatio)

            canvas.save()
            canvas.translate(
                (imgX - image.width * ratio / 2).toFloat(),
                (imgY - image.height * ratio / 2).toFloat()
            )
            canvas.scale(ratio.toFloat(), ratio.toFloat())
            canvas.drawBitmap(image, 0f, 0f, paint)
            canvas.restore()
        }
    }

    private fun drawPrizeText(canvas: Canvas) {
        paint.color = Color.BLACK
        // 在扇区上绘制奖品名字
        for (i in 0 until prizeCount) {
            val startAngle = 360f * i / prizeCount

            val fullPath = Path()
            fullPath.addArc(rectArc, startAngle, 360f / prizeCount)

            val pathMeasure = PathMeasure(fullPath, false)
            val textPath = Path()
            val middlePos = pathMeasure.length * 0.5f

            pathMeasure.getSegment(middlePos - 100, middlePos + 100, textPath, true)

            val text = prizes[i]
            paint.textSize = (rectArc.height() * 0.05.toFloat())
            paint.textAlign = Paint.Align.CENTER
            canvas.drawTextOnPath(text, textPath, 0f, 100f, paint)
        }
    }

    private fun drawBackground(canvas: Canvas) {
        for (i in 0 until prizeCount) {
            paint.color = prizeColors[i]
            val startAngle = 360f * i / prizeCount
            val sweepAngle = 360f / prizeCount
            canvas.drawArc(rectArc, startAngle, sweepAngle, true, paint)
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {
            rotating()
            return true
        }
        return super.onTouchEvent(event)
    }

    private fun rotating() {
        val targetRotation = totalRotation + 360 * (4 + Math.random() * 4).toFloat()

        // 动画时长，由外部调用者设定
        val animator = ValueAnimator.ofFloat(totalRotation, targetRotation)
        animator.apply {
            interpolator = DecelerateInterpolator()
            this.duration = animationDuration.toLong()
            addUpdateListener {
                totalRotation = animatedValue as Float
                invalidate()
            }
            start()
        }
    }
}